<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addUserDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">

            <el-row :class="['bdbottom',index1 === 0? 'bdtop' :'','vcenter']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="19">
                <!-- for循环嵌套，渲染二级权限 -->
                <el-row :class="[index2 === 0 ? '': 'bdtop','vcenter']"  v-for="(item2,index2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightsById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag closable v-for="(item3,index3) in item2.children" :key="item3.id" type="warning" @close="removeRightsById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>

          </template>
        </el-table-column>

        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRolesById(scope.row.id)">删除</el-button>
            <!-- 提示按键信息，分配角色按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)">分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="50%"
      @close="addUserDialogClose"
      >
      <el-form :model="rolesForm" :rules="rolesFormRules" ref="rolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改角色对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @close="editUserDialogClosed"
      >
      <el-form :model="editRolesFrom" :rules="editRolesFromRules" ref="editRolesFromRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsDialogClosed"
      >
      <el-tree :data="rightsList"
      :props="treeProps"
      :default-expand-all="true"
      node-key="id"
      show-checkbox
      :default-checked-keys="defKeys"
      ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
  export default{
    data(){
      return{
        //所有角色列表的数据
        rolesList:[],
        addUserDialogVisible:false,
        rolesForm:{
          roleName:'',
          roleDesc:''
        },
        rolesFormRules:{
          roleName:[{
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            }],
          roleDesc:[{
              required: true,
              message: '请输入角色描述',
              trigger: 'blur'
            }]
        },
        editUserDialogVisible:false,
        editRolesFrom:{},
        editRolesFromRules:{
          roleName:[{
              required: true,
              message: '请输入角色名称',
              trigger: 'blur'
            }],
          roleDesc:[{
              required: true,
              message: '请输入角色描述',
              trigger: 'blur'
            }]
        },
        //分配权限
        setRightsDialogVisible:false,
        //所有权限的数组
        rightsList:[],
        treeProps:{
          children:'children',
          label:'authName'
        },
        defKeys:[],
        roleId:''
      }
    },
    created(){
      this.getRolesList()
    },
    methods:{
      async getRolesList(){
        const {data:res} = await this.$http.get('roles')
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.rolesList = res.data
        // console.log(this.rolesList)
      },
      //取消
      addUserDialogClose(){
        this.$refs.rolesFormRef.resetFields()
      },
      //确认添加角色
      addRoles(){
        this.$refs.rolesFormRef.validate(async valid => {
          //预验证
          if(!valid) return
          //通过才发起请求
          const {data:res} = await this.$http.post('roles',this.rolesForm)
          // console.log(res)
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)

          this.$message.success(res.meta.msg)
          this.addUserDialogVisible = false
          this.getRolesList()
        })
      },
      //查询
      async editUserDialog(id){

        const {data : res } = await this.$http.get(`roles/${id}`)
        // console.log(res)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editRolesFrom = res.data

        // console.log(this.editRolesFrom)

        this.editUserDialogVisible = true

      },
      editUserDialogClosed(){
        this.$refs.editRolesFromRef.resetFields()
      },
      //编辑
      editRoles(){
        this.$refs.editRolesFromRef.validate(async valid => {
          if(!valid) return
          //通过，请求
          const {data: res} = await this.$http.put(`roles/${this.editRolesFrom.roleId}`,this.editRolesFrom)
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

          this.$message.success(res.meta.msg)
          this.editUserDialogVisible =false
          this.getRolesList()
        })
      },
      //删除
       async removeRolesById(id){
        //弹框
        const confirmRole = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).catch(err => err)

        if(confirmRole !== 'confirm') return this.$message.success('已经取消了删除')
        const {data : res } = await this.$http.delete(`roles/${id}`)

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)


        this.getRolesList()
        this.$message.success(res.meta.msg)
      },
      //根据ID删除对应权限
      async removeRightsById(role,rightID){
        //弹框
        const confirmres = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).catch(err => err)

        if(confirmres !== 'confirm') return this.$message.success('已经取消了删除')

        //用户确定要删除
        const {data : res } = await this.$http.delete(`roles/${role.id}/rights/${rightID}`)

        // console.log(res)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)

        //不用调用this.geiuserlist()  用这个就可以刷新
        role.children = res.data
        this.$message.success(res.meta.msg)


      },
      //展示分配权限的对话框
      async showSetRightsDialog(role){
        this.roleId = role.id
        // 获取所有权限数据
        const {data:res} = await this.$http.get('rights/tree')
        // console.log(res)

        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.rightsList = res.data
        this.getLeafKeys(role,this.defKeys)
        // console.log(this.rightsList)
        this.setRightsDialogVisible = true
      },
      //通过递归的形式获取角色的三级权限id
      getLeafKeys(node,arr){
        if(!node.children){
          return arr.push(node.id)
        }

        node.children.forEach(item =>
        this.getLeafKeys(item,arr))
      },
      setRightsDialogClosed(){
        this.defKeys = []
      },
      //点击分配角色权限
      async allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const { data : res } =
        await this.$http.post(`roles/${this.roleId}/rights`,{ rids : idStr })
        // console.log(res)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getRolesList()
        this.setRightsDialogVisible = false
        this.$message.success(res.meta.msg)

      }


    }

  }
</script>

<style lang="less" scoped>

  .el-tag{
    margin: 7px;
  }

  .bdtop{
    border-top:1px solid #eee ;
  }

  .bdbottom{
    border-bottom:1px solid #eee ;
  }

  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
